<?php
// web/model/post.php

// REQUIRE:
if(version_compare(PHP_VERSION, '5.3.0', '>=')) { require_once __DIR__.'/../include.inc'; } 
else { require_once dirname(__FILE__).'/../include.inc'; }

class Model
{
	public static $database;
	
	public static function get_database() 
	{
		if(self::$database == null) {
			self::$database = new Database(HOSTNAME, DATABASE, USERNAME, PASSWORD);
		}
		return self::$database->get();
	}
}

class M_Posts extends Model
{
	static $post_count = 0;
	public $post_array = array();

	public function get_posts()
	{
		$sql = "SELECT * FROM `posts` ORDER BY ID DESC";
		foreach (parent::get_database()->query($sql) as $result)
		{
			array_push($this->post_array, new Post($result['subject'], $result['author'], $result['date'], $result['message']));
			self::$post_count++;
		}

		return $this->post_array;
	}
	
	public function get_post($id)
	{
		$post = array(); 
		try 
		{
			$this->get_posts();
			if(isset($this->post_array[$id]))
				$post = $this->post_array[$id];
			else 	
			{
				$post = null;
				throw new Exception('Post id not found.');
			}
		}
		catch(Exception $e)
		{
			return "Caught exception: { $e->getMessage() }.\n";
		}
		return $post;
	}
}

?>